package top.bigdata.config;

import org.apache.ibatis.type.*;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

@MappedJdbcTypes(JdbcType.ARRAY)
@MappedTypes(List.class)
public class HiveArrayTypeHandler extends BaseTypeHandler<List<String>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    List<String> parameter, JdbcType jdbcType) throws SQLException {
        // 将 List 转换为逗号分隔的字符串
        String arrayString = String.join(",", parameter);
        ps.setString(i, arrayString);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String arrayString = rs.getString(columnName);
        return convertStringToList(arrayString);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String arrayString = rs.getString(columnIndex);
        return convertStringToList(arrayString);
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String arrayString = cs.getString(columnIndex);
        return convertStringToList(arrayString);
    }

    private List<String> convertStringToList(String arrayString) {
        if (arrayString == null || arrayString.isEmpty()) {
            return null;
        }
        // 移除数组的括号（如果存在）
        String cleanString = arrayString.replaceAll("[\\[\\]]", "");
        List<String> list = Arrays.asList(cleanString.split(","));
        list.replaceAll(s -> {
            // 去除字符串中的引号
            return s.substring(1, s.length() - 1);
        });
        return list;
    }
}